package com.robusta.spreadsheet.model.impl;

import com.robusta.spreadsheet.model.Workbook;
import com.robusta.spreadsheet.model.WorkbookTemplate;
import com.robusta.spreadsheet.model.Worksheet;
import com.robusta.spreadsheet.model.WorksheetTemplate;
import com.robusta.spreadsheet.model.exception.WorkbookException;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.Map;

import static com.google.common.collect.Maps.newHashMap;
import static com.robusta.spreadsheet.model.impl.RobustaWorkbookFactory.newWorksheet;

/**
 */
public class RobustaWorkbook implements Workbook {
    private org.apache.poi.ss.usermodel.Workbook workbook;
    private WorkbookTemplate template;
    private Map<WorksheetTemplate, Worksheet> worksheets = newHashMap();

    protected RobustaWorkbook(org.apache.poi.ss.usermodel.Workbook workbook, WorkbookTemplate template) throws WorkbookException {
        this.template = template;
        this.workbook = workbook;
        initializeWorksheets();
    }

    private void initializeWorksheets() throws WorkbookException {
        for (WorksheetTemplate worksheetTemplate : template.getSpreadsheetTemplates()) {
            Sheet sheet = workbook.getSheetAt(worksheetTemplate.getSheetIndex());
            if(sheet == null) {
                throw new WorkbookException(String.format("Unable to load worksheet described by template: %s", worksheetTemplate));
            }
            worksheets.put(worksheetTemplate, newWorksheet(this, sheet, worksheetTemplate));
        }
    }

    @Override
    public Worksheet getSheetFor(WorksheetTemplate template) throws WorkbookException {
        if(worksheets.containsKey(template)) {
            return worksheets.get(template);
        }
        throw new WorkbookException(String.format("Unable to locate a worksheet in workbook described by template: %s", template));
    }
}
